package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
@Slf4j
@Api(tags = "地址簿接口")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping("/user/addressBook")
    @ApiOperation("新增地址")
    public Result addAddress(@RequestBody AddressBook addressBook){
        log.info("新增地址");
        addressService.save(addressBook);
        return Result.success();
    }

    @GetMapping("/user/addressBook/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list(){
        log.info("查询当前登录用户的所有地址信息");
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook>list=addressService.list(addressBook);
        return Result.success(list);
    }
    @GetMapping("/user/addressBook/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getById(@PathVariable  Long id){
        log.info("根据id查询地址");
        AddressBook addressBook=addressService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping("/user/addressBook")
    @ApiOperation("根据id修改地址")
    public Result updateById(@RequestBody AddressBook addressBook){
        log.info("根据id修改地址");
        addressService.update(addressBook);
        return Result.success();
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/user/addressBook/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址");
        addressService.setDefault(addressBook);
        return Result.success();
    }
    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping("/user/addressBook")
    @ApiOperation("根据id删除地址")
    public Result deleteById(Long id) {
        addressService.deleteById(id);
        return Result.success();
    }
    /**
     * 查询默认地址
     */
    @GetMapping("/user/addressBook/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> getDefault() {

        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressService.list(addressBook);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }
        return Result.error("没有查询到默认地址");
    }

}
